package com.mohan.calligraphy.exception;

import com.mohan.calligraphy.constant.CalligraphyHttpStatus;
import com.mohan.calligraphy.result.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author mohan
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public R runtimeException(RuntimeException rx) {
        if (rx instanceof ParamException) {
            log.error("params error exception: ", rx.getMessage());
            return R.error(rx.getMessage());
        }
        if (rx instanceof BusinessException) {
            log.error("unknown error exception", rx);
            return R.error(rx.getMessage());
        }
        log.error("unknown error exception", rx);
        return R.error();
    }

    @ExceptionHandler(value = Error.class)
    @ResponseBody
    public R error(Error rx) {
        log.error("unknown exception", rx);
        return R.error();
    }

    @ExceptionHandler(value = UnauthenticatedException.class)
    @ResponseBody
    public R unauthorizedException(Exception ex) {
        return R.error(CalligraphyHttpStatus.CalligraphyErrorMessage.UNAUTHENTICATEDEXCEPTION);
    }

    @ExceptionHandler(value = AuthorizationException.class)
    @ResponseBody
    public R authorizationException(Exception ex) {
        return R.error(CalligraphyHttpStatus.CalligraphyErrorMessage.AUTHORIZATIONEXCEPTION);
    }
}
